package com.lanou3g.HW_0514;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by dllo on 18/5/14.
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/b")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.查一下是否有这个用户
        // 条件是 用户名,和密码 都匹配上
        String checkLogin = "SELECT * FROM users WHERE username = ? AND pwd = ?";
        PreparedStatement statement = JDBCUtil.getPreStatement(checkLogin);
        // 设置值
        try {
            String username = request.getParameter("username");
            String pwd = request.getParameter("password");
            statement.setString(1, username);
            statement.setString(2, pwd);

            ResultSet rs = statement.executeQuery();

            if (rs.next()) {

                String dbUsername = rs.getString("username");
                String dbpwd = rs.getString("pwd");

                if (dbUsername.equals(username) && dbpwd.equals(pwd)) {
                    System.out.println("登入成功");
                } else {
                    System.out.println("登入失败");
                }
            }
            rs.close();
            JDBCUtil.closeResource(statement);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
